<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    :width="dialogWidth"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item label="所属机构" prop="">
        <el-tree-select
          v-model="form.orgArr"
          :data="treePartData"
          multiple
          filterable
          :render-after-expand="false"
          show-checkbox
          style="width: 100%"
          check-strictly
          check-on-click-node
        />
      </el-form-item>
      <el-form-item label="所属组别" prop="">
        <el-tree-select
          v-model="form.groupArr"
          :data="treeRoleData"
          multiple
          filterable
          :render-after-expand="false"
          show-checkbox
          style="width: 100%"
          check-strictly
          check-on-click-node
        />
      </el-form-item>
      <el-form-item label="用户名" prop="username">
        <el-input v-model.trim="form.username" />
      </el-form-item>
      <el-form-item label="姓名" prop="realname">
        <el-input v-model.trim="form.realname" size="medium" />
      </el-form-item>
      <el-form-item label="手机号" prop="telphone">
        <el-input v-model.trim="form.telphone" size="medium" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model.trim="form.password" size="medium" type="password" />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio v-model="form.status" checked label="normal">在职</el-radio>
        <el-radio v-model="form.status" label="hidden">离职</el-radio>
      </el-form-item>

      <el-form-item
        v-if="webconfig?.is_has_lastHandlingPersonnel == 1"
        label="职务"
      >
        <el-input v-model.trim="form.job" size="medium" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  import { toRaw } from 'vue'
  import { dialogWidth } from '@/config'
  import { doAdd, doEdit } from '@/api/userManagement'
  import { getList as getPartList } from '@/api/departmentManagement'
  import { getList as getRoleList } from '@/api/roleManagement'
  import { convertedTreeNode } from '@/utils/index'

  export default defineComponent({
    name: 'UserManagementEdit',
    components: {},
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        treePartData: [],
        treeRoleData: [],
        form: {
          username: '',
          password: '',
          telphone: '',
          realname: '',
          orgArr: [],
          orgNameArr: {},
          orgname: '',
          groupArr: [],
          status: 'normal',
          job: '',
        },
        detail: {},
        rules: {
          username: [
            { required: true, trigger: 'blur', message: '请输入用户名' },
          ],
          password: [
            { required: true, trigger: 'blur', message: '请输入密码' },
          ],
          email: [{ required: true, trigger: 'blur', message: '请输入邮箱' }],
          roles: [{ required: true, trigger: 'blur', message: '请选择角色' }],
        },
        title: '',
        dialogFormVisible: false,
        dialogWidth,
      })

      const fetchPartData = async () => {
        state.listLoading = true
        const {
          data: { list },
        } = await getPartList(state.queryForm)

        state.treePartData = convertedTreeNode(list)
      }

      const fetchRoleData = async () => {
        state.listLoading = true
        const {
          data: { list },
        } = await getRoleList(state.queryForm)

        state.treeRoleData = convertedTreeNode(list)
      }

      const showEdit = (row) => {
        fetchPartData()
        fetchRoleData()

        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'

          if (row.org != '') {
            row.orgArr = row.org.map((item) => `${item.orgid}`)
          }
          if (row.group != '') {
            row.groupArr = row.group.map((item) => parseInt(item.groupid))
          }

          state.form = row
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          roles: [],
          orgArr: [],
          groupArr: [],
        }
        state.dialogFormVisible = false
      }

      const confirm = () => {
        if (state.title == '添加') {
          add()
        } else {
          save()
        }
      }

      const add = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            state.form.orgid = state.form.orgArr.join(',')
            state.form.groupid = state.form.groupArr.join(',')

            const { msg } = await doAdd(state.form)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            state.form.orgid = state.form.orgArr.join(',')
            state.form.groupid = state.form.groupArr.join(',')

            // 如果密码没有修改，不传密码
            const post = {
              id: state.form.id,
              orgname: state.form.orgname,
              orgid: state.form.orgid,
              groupid: state.form.groupid,
              username: state.form.username,
              realname: state.form.realname,
              telphone: state.form.telphone,
              status: state.form.status,
            }

            if (state.webconfig?.is_has_lastHandlingPersonnel == 1) {
              post.job = state.form.job
            }

            // 如果密码已经修改，传修改后的密码

            const obj1 = toRaw(state.form)
            const obj2 = toRaw(state.detail)
            if (obj1.password != obj2.password) {
              post.password = obj1.password
            }

            const { msg } = await doEdit({
              ...post,
            })

            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      onMounted(() => {})

      return {
        ...toRefs(state),
        showEdit,
        fetchPartData,
        fetchRoleData,
        close,
        confirm,
        add,
        save,
        // handleCheck,
      }
    },
  })
</script>
<style lang="scss" scoped>
  :deep() {
    .vue-treeselect__control {
      border-radius: 2px;
    }
    .el-form-item__content {
      line-height: normal;
    }
    .tree-select,
    .vue-treeselect {
      &__multi-value-label {
        // width: 85%;
        display: block;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        line-height: normal;
      }
      .vue-treeselect__multi-value-item-container {
        padding-top: 2px;
      }
      &--has-value,
      &__multi-value {
        display: flex;
        margin-bottom: 0;
      }
      &__limit-tip-text {
        min-width: 40px;
      }
      &__x-container {
        position: absolute;
        z-index: 100;
        top: 13px;
        right: 20px;
      }

      &__menu {
        // width: max-content !important;
        width: 100%;
        // max-width: 20em;
      }
      &__control {
        height: 32px;
      }
      &__placeholder,
      &__single-value {
        line-height: 32px;
      }
    }
  }
</style>
